package com.itgacl.magic4j.libcommon.component.ws.cluster.mq;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.TransactionSendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Slf4j
@ConditionalOnExpression("${ws.enable} == true && '${ws.cluster.type}'.equals('mq')")
@Component
public class RocketMqSender {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送消息
     * @param msg
     * @param topic
     */
    public void sendMessage(String msg, String topic) {
        rocketMQTemplate.convertAndSend(topic, msg);
    }

    /**
     * 发送事务消息
     * @param msg
     * @param topic
     */
    public void sendMessageInTransaction(String msg, String topic) {
        Message<String> message = MessageBuilder.withPayload(msg)
                .setHeader(RocketMQHeaders.TRANSACTION_ID, UUID.randomUUID().toString())
                .build();
        TransactionSendResult sendResult = rocketMQTemplate.sendMessageInTransaction(topic, message, topic);
        log.info("事务消息发送结果：{}", sendResult.toString());
    }
}
